package com.hqyj.springbootday03.modules.common.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * Exception Controller
 */
@ControllerAdvice
public class ExceptionController {
	
	@ExceptionHandler(value = {Exception.class})
	public ModelAndView handleException(HttpServletRequest request, Exception ex) {
		
		// 初始化返回数据
		HttpStatus httpStatus = HttpStatus.OK;
		String message = "";
		String data = "";
		
		// 根据异常的类型，包装返回数据
		if (ex instanceof UnauthorizedException) {
			httpStatus = HttpStatus.FORBIDDEN;
			message = "没有权限";
			data = "/common/403";
		} else {
			httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
			message = "内部错误";
			data = "/common/500";
		}
		
		// 判断请求是否为接口
		if (isInterface(request)) {
			return returnJson(httpStatus, message, data);
		} else {
			return returnPage(data, httpStatus);
		}
	}
	
	// 判断请求是否为接口
	private boolean isInterface(HttpServletRequest request) {
		HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute(
				"org.springframework.web.servlet.HandlerMapping.bestMatchingHandler");
		
		RestController[] annotations1 = handlerMethod.getBeanType().getAnnotationsByType(RestController.class);
		ResponseBody[] annotations2 = handlerMethod.getBeanType().getAnnotationsByType(ResponseBody.class);
		ResponseBody[] annotations3 = handlerMethod.getMethod().getAnnotationsByType(ResponseBody.class);
		
		return annotations1.length > 0 || annotations2.length > 0 || annotations3.length > 0;
	}
	
	// 返回页面
	public ModelAndView returnPage(String data, HttpStatus httpStatus) {
//		return new ModelAndView("redirect:" + data, httpStatus);
		return new ModelAndView(new RedirectView(data));
	}
	
	// 返回 json 数据
	public ModelAndView returnJson(HttpStatus httpStatus, String message, String data) {
		ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
		modelAndView.addObject("status", httpStatus.value());
		modelAndView.addObject("message", message);
		modelAndView.addObject("data", data);
		return modelAndView;
	}

}
